import 'package:flutter/material.dart';
import '../models/exhibition.dart';
import '../services/exhibition_service.dart';
import '../widgets/exhibition_card.dart';
import '../theme/colors.dart';
import 'exhibition_detail_screen.dart';

class ExhibitionsScreen extends StatefulWidget {
  const ExhibitionsScreen({super.key});

  @override
  State<ExhibitionsScreen> createState() => _ExhibitionsScreenState();
}

class _ExhibitionsScreenState extends State<ExhibitionsScreen> {
  final ExhibitionService _exhibitionService = ExhibitionService();
  List<Exhibition> _exhibitions = [];
  List<Exhibition> _filteredExhibitions = [];
  ExhibitionFilter _currentFilter = ExhibitionFilter.all;
  bool _isLoading = true;
  String _searchQuery = '';

  @override
  void initState() {
    super.initState();
    _loadExhibitions();
  }

  Future<void> _loadExhibitions() async {
    setState(() {
      _isLoading = true;
    });

    try {
      final exhibitions = await _exhibitionService.getAllExhibitions();
      setState(() {
        _exhibitions = exhibitions;
        _filteredExhibitions = exhibitions;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('加载展览失败: $e')),
        );
      }
    }
  }

  void _filterExhibitions(ExhibitionFilter filter) async {
    setState(() {
      _currentFilter = filter;
      _isLoading = true;
    });

    try {
      final exhibitions = await _exhibitionService.getExhibitionsByFilter(filter);
      setState(() {
        _filteredExhibitions = exhibitions;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
    }
  }

  void _searchExhibitions(String query) {
    setState(() {
      _searchQuery = query;
      if (query.isEmpty) {
        _filteredExhibitions = _exhibitions;
      } else {
        _filteredExhibitions = _exhibitions
            .where((exhibition) =>
                exhibition.title.toLowerCase().contains(query.toLowerCase()) ||
                exhibition.description.toLowerCase().contains(query.toLowerCase()))
            .toList();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeColors.background,
      appBar: AppBar(
        title: const Text('文化展览'),
        backgroundColor: ThemeColors.primary,
        foregroundColor: Colors.white,
        elevation: 0,
      ),
      body: Column(
        children: [
          // 搜索栏
          Container(
            padding: const EdgeInsets.all(16),
            color: Colors.white,
            child: TextField(
              onChanged: _searchExhibitions,
              decoration: InputDecoration(
                hintText: '搜索展览...',
                prefixIcon: const Icon(Icons.search),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(12),
                  borderSide: BorderSide.none,
                ),
                filled: true,
                fillColor: ThemeColors.background,
              ),
            ),
          ),
          // 筛选标签
          Container(
            height: 50,
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: ListView(
              scrollDirection: Axis.horizontal,
              children: ExhibitionFilter.values.map((filter) {
                final isSelected = _currentFilter == filter;
                return Padding(
                  padding: const EdgeInsets.only(right: 8),
                  child: FilterChip(
                    label: Text(_getFilterLabel(filter)),
                    selected: isSelected,
                    onSelected: (_) => _filterExhibitions(filter),
                    backgroundColor: Colors.white,
                    selectedColor: ThemeColors.primary.withOpacity(0.2),
                    checkmarkColor: ThemeColors.primary,
                  ),
                );
              }).toList(),
            ),
          ),
          // 展览列表
          Expanded(
            child: _isLoading
                ? const Center(child: CircularProgressIndicator())
                : _filteredExhibitions.isEmpty
                    ? const Center(
                        child: Text(
                          '暂无展览',
                          style: TextStyle(fontSize: 16, color: Colors.grey),
                        ),
                      )
                    : ListView.builder(
                        padding: const EdgeInsets.all(16),
                        itemCount: _filteredExhibitions.length,
                        itemBuilder: (context, index) {
                          final exhibition = _filteredExhibitions[index];
                          return Padding(
                            padding: const EdgeInsets.only(bottom: 16),
                            child: ExhibitionCard(
                              exhibition: exhibition,
                              onTap: () {
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) => ExhibitionDetailScreen(
                                      exhibitionId: exhibition.id,
                                    ),
                                  ),
                                );
                              },
                            ),
                          );
                        },
                      ),
          ),
        ],
      ),
    );
  }

  String _getFilterLabel(ExhibitionFilter filter) {
    switch (filter) {
      case ExhibitionFilter.all:
        return '全部';
      case ExhibitionFilter.ongoing:
        return '进行中';
      case ExhibitionFilter.upcoming:
        return '即将开始';
      case ExhibitionFilter.completed:
        return '已结束';
      case ExhibitionFilter.ended:
        return '已结束';
      case ExhibitionFilter.virtual:
        return '虚拟展览';
      case ExhibitionFilter.hot:
        return '热门';
      case ExhibitionFilter.bookmarked:
        return '已收藏';
      case ExhibitionFilter.free:
        return '免费';
      case ExhibitionFilter.traditional:
        return '传统文化';
      case ExhibitionFilter.folk:
        return '民俗文化';
      case ExhibitionFilter.historical:
        return '历史文化';
      case ExhibitionFilter.modern:
        return '现代艺术';
      case ExhibitionFilter.interactive:
        return '互动体验';
      case ExhibitionFilter.featured:
        return '精选推荐';
    }
  }
}